package com.jet.core.model.vo;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.fasterxml.jackson.annotation.JsonIgnore;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

import java.util.Collections;
import java.util.List;

@ApiModel
@Data
public class PageVo<T> {

    /**
     * 每页显示条数，默认 10
     */
    @ApiModelProperty(value = "每页大小，默认10")
    private long pageSize = 10;

    /**
     * 当前页
     */
    @ApiModelProperty(value = "当前页，默认1")
    private long pageIndex = 1;

    /**
     * 查询数据列表
     */
    private List<T> data;

    @ApiModelProperty("数据总页数")
    private int rows;

    @ApiModelProperty("数据总数")
    private long total = 0;

    /**
     * 是否进行 count 查询
     */
    @JsonIgnore
    private boolean isSearchCount = true;

    @JsonIgnore
    private String countId;
    @JsonIgnore
    private Long maxLimit;
    @JsonIgnore
    private boolean optimizeCountSql;

    @JsonIgnore
    public boolean getSearchCount() {
        if (total < 0) {
            return false;
        }
        return isSearchCount;
    }

    public static <T> PageVo<T> result() {
        PageVo<T> page = new PageVo<T>();
        page.setData(Collections.emptyList());
        return page;
    }

    public static <T> PageVo<T> result(IPage<T> result) {
        PageVo<T> page = new PageVo<T>();
        if (CollUtil.isEmpty(result.getRecords())) {
            page.data = Collections.emptyList();
        } else {
            page.data = result.getRecords();
        }
        page.pageIndex = result.getCurrent();
        page.pageSize = result.getSize();
        page.total = result.getTotal();
        return page;
    }

    public static <T> PageVo<T> result(IPage<?> result, List<T> items) {
        PageVo<T> page = new PageVo<T>();
        if (CollUtil.isEmpty(items)) {
            page.data = Collections.emptyList();
        } else {
            page.data = items;
        }
        page.pageIndex = result.getCurrent();
        page.pageSize = result.getSize();
        page.total = result.getTotal();
        return page;
    }

    public static <T> PageVo<T> result(long pageIndex, long pageSize, long total, List<T> items) {
        PageVo<T> page = new PageVo<T>();
        if (CollUtil.isEmpty(items)) {
            page.data = Collections.emptyList();
        } else {
            page.data = items;
        }
        page.pageIndex = pageIndex;
        page.pageSize = pageSize;
        page.total = total;
        return page;
    }
}
